package com.mrzhou.common.feign.factory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.mrzhou.common.feign.client.ISystemClient;
import com.mrzhou.common.feign.client.IUserClient;
import com.mrzhou.common.feign.fallback.SystemClientFallback;
import com.mrzhou.common.feign.fallback.UserClientFallback;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.utils.JacksonUtil;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SystemClientFallbackFactory implements FallbackFactory<ISystemClient> {

    private String DEFAULT_MSG = "系统服务服务繁忙, 请稍后重试";

    @Override
    public ISystemClient create(Throwable throwable) {
        log.error("cloud-system远程服务产生的异常: {}", throwable);
        if(throwable instanceof FeignException) {
            FeignException feignException = (FeignException) throwable;
            // 获取返回的json格式
            String resultStr = feignException.contentUTF8();
            R<String> result = JacksonUtil.parseObject(resultStr, new TypeReference<R<String>>() {});
            return new SystemClientFallback(result != null && StringUtils.isNotBlank(result.getMsg()) ? result.getMsg() : DEFAULT_MSG);
        }
        return new SystemClientFallback(DEFAULT_MSG);
    }
}
